package map.android.baidu.carpool.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.mapframework.component.comcore.exception.ComException;
import com.baidu.mapframework.component.comcore.impl.message.DefaultComRequestFactory;
import com.baidu.mapframework.component.comcore.impl.message.params.ComBaseParams;
import com.baidu.mapframework.component.comcore.manager.ComponentManager;
import com.baidu.mapframework.component.comcore.message.ComRequest;
import com.baidu.sapi2.callback.SapiCallback;
import com.baidu.sapi2.result.GetDynamicPwdResult;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.animation.AnimationListenerForCarpool;
import map.android.baidu.carpool.animation.AnimationUtilsForCarpool;
import map.android.baidu.carpool.utils.SmsUtils.OnVerCodeCallBack;

/**
 * 通过手机号登录百度账号
 * 
 * @author chenlei18
 */
public class CarUserLoginDialog extends Dialog {
	public static final String LOGTAG = "CarUserLoginDialog";

	private static final double SCALE = 0.9;
    private View mViewMain;
	private TextView mTitleTextView;
	private EditText mCodeEditText;
	private TextView mOkButton;
	private TextView mCancelButton;
	private TextView mGetIdentifyCodeButton;
	private EditText mPhoneEd;
	private Activity mActivity;
	private CallBack mCallBack;
	private String phoneNum;
	
	private SmsUtils mSmsUtils;

	public void showDialog(CarUserLoginDialog carInPutDialog, View.OnClickListener okListener) {
		carInPutDialog.setOkButtonOnClickListener(okListener);
		carInPutDialog.show();
	}
	
	public void showDialog(CarUserLoginDialog carInPutDialog, CallBack okListener) {
		carInPutDialog.setOkButtonOnClickListener(okListener);
		carInPutDialog.show();
	}

	public CarUserLoginDialog(Activity activity, int titleId) {
		super(activity);
		if (activity == null) {
			return;
		}
		initUI(activity, titleId);
	}

	
	private void registerSmsListener() {
		mSmsUtils = new SmsUtils(mActivity);
		mSmsUtils.setOnVerCodeListener(new OnVerCodeCallBack() {
			@Override
			public void onVerCodeSetText(String str) {
				mCodeEditText.clearFocus();
				mCodeEditText.setText(str);
			}
		});
		mSmsUtils.registerSMS();
	}
	
	public String returnInputValue(CarUserLoginDialog carInPutDialog) {
		String inPutString = carInPutDialog.mCodeEditText.getText().toString();
		return inPutString;
	}

	public CarUserLoginDialog(Activity activity, String title) {
		super(activity, 0);
		if (activity == null) {
			return;
		}
		initUI(activity, title);
	}

	private void initUI(Activity activity, int titleId) {
		String title = APIProxy.res().getString(titleId);
		mActivity = activity;
		initUI(activity, title);
	}

	@SuppressWarnings("deprecation")
	private void initUI(Activity activity, String title) {
		registerSmsListener();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setCancelable(false);

		mViewMain = APIProxy.res().inflate(R.layout.carpool_login_dialog, null);
		AnimationUtilsForCarpool.getInstance().translateTopToBottom(mViewMain);
		setContentView(mViewMain);

  
		mGetIdentifyCodeButton = (TextView) mViewMain.findViewById(R.id.car_get_verify_code_button);
		mPhoneEd = (EditText) mViewMain.findViewById(R.id.car_phone_idenfy);
		mTitleTextView = (TextView) mViewMain.findViewById(R.id.car_input_dialog_title_textview);
		mCodeEditText = (EditText) mViewMain.findViewById(R.id.car_idenfy_info_edit);
		mCancelButton = (TextView) mViewMain.findViewById(R.id.car_input_dialog_cancel_button);
		mOkButton = (TextView) mViewMain.findViewById(R.id.car_input_dialog_ok_button);

		mOkButton.setEnabled(false);
		mCancelButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dismissDialog();
			}
		});
		mOkButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mCodeEditText.clearFocus();
				dismissDialog();
			}
		});
		mTitleTextView.setText(title);

		mGetIdentifyCodeButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				getIdentifyCode(true);
			}
		});
		
		mPhoneEd.postDelayed(new Runnable() {
            
            @Override
            public void run() {
                HelpUtils.showSoftKeyboard(mPhoneEd);
            }
        }, 350);

	}

	/**
	 * @param status  分支  从不同地方验证
	 * @return
	 */
	protected boolean getIdentifyCode(boolean status) {

		if(!NetworkUtils.checkNetworkStatus(true)){
			return false;
		}
		HelpUtils.closeSoftKeyboard(mPhoneEd);
		phoneNum = mPhoneEd.getText().toString().trim();
		if (phoneNum == null || phoneNum.equals("")) {
			Toast.makeText(mActivity, "手机号不能为空", 1).show();
			return false;
		}
		if (!phoneNum.substring(0, 1).equals("1")) {
			Toast.makeText(mActivity, "手机号无效，请重新验证", 1).show();
			return false;
		}

		if (!isPhoneNum(phoneNum)) {
			Toast.makeText(mActivity, "手机号错误", 1).show();
			return false;
		} else {
			if (phoneNum.equals(getPhoneNumFromPreference(mActivity))) {
				Toast.makeText(mActivity, "该号码已绑定，不用再次验证", 1).show();
				return false;
			} else {
				if(status){
					getIdentifyCode(phoneNum);
					mPhoneEd.clearFocus();
					mCodeEditText.requestFocus();
					mGetIdentifyCodeButton.setEnabled(false);
				}
			}
		}
		
		return true;

	}

	/**
	 * 获取验证码  （百度账号）
	 * 
	 * @param phoneNum
	 */
	private void getIdentifyCode(String phoneNum) {

		SapiCallback<GetDynamicPwdResult> callback = new SapiCallback<GetDynamicPwdResult>() {
            @Override
            public void onSuccess(GetDynamicPwdResult getDynamicPwdResult) {
                ToastForCarpool.show(mActivity, "发送成功");
				mGetIdentifyCodeButton.setEnabled(false);
				mOkButton.setEnabled(true);
            }

            @Override
            public void onFailure(GetDynamicPwdResult getDynamicPwdResult) {
                if (getDynamicPwdResult != null) {
                    ToastForCarpool.show(mActivity, getDynamicPwdResult.getResultMsg());
                } else {
                    ToastForCarpool.show(mActivity, "发送失败");
                }
				mGetIdentifyCodeButton.setEnabled(true);
            }

            @Override
            public void onStart() {

            }

            @Override
            public void onFinish() {

            }
		};
		DefaultComRequestFactory factory = new DefaultComRequestFactory();
		ComRequest request = factory.newComRequest("mainmap", ComRequest.METHOD_INVOKE);
		ComBaseParams params = new ComBaseParams();
		params.setTargetParameter("invoke_get_dynic_pwd_new");
		params.putBaseParameter("phone_num", phoneNum);
		params.putBaseParameter("callback", callback);
		request.setParams(params);
		try {
			ComponentManager.getComponentManager().invoke(request);
		} catch (ComException e) {
			e.printStackTrace();
		}

	}

	protected void showToast(int errCode) {
        switch (errCode) {
            case 16:
				ToastForCarpool.show(mActivity, "验证码发送过多，请24小时后再试");
                break;
            default:
				ToastForCarpool.show(mActivity, "验证码发送过多，请24小时后再试");
                break;
        }
    }

    public static String getPhoneNumFromPreference(Context activty) {
		SharedPreferences sharedPreferences = activty.getSharedPreferences("taxi_phonenum", 0);
		String tel = sharedPreferences.getString("phonenum", "");
		return tel;
	}

	private boolean isPhoneNum(String phoneNum) {
		if (phoneNum == null || phoneNum.equals("") || phoneNum.length() != 11) {
			return false;
		}
		return true;
	}

	public void setTitle(int titleId) {
		String title = APIProxy.res().getString(titleId);
		setTitle(title);
	}

	public void setTitle(String title) {
		if (mTitleTextView != null) {
			mTitleTextView.setText(title);
		}
	}

	public void setOkButtonOnClickListener(final CallBack l) {
		if (l == null) {
			return;
		}
		if (mOkButton != null) {
			mOkButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					
//					 TODO 验证手机号码 和 验证码
					String code = mCodeEditText.getText().toString();
					if(!getIdentifyCode(false))
						return;
					if(code.equals("")&&code.replace(" ", "").equals("")){
						Toast.makeText(mActivity, "请输入验证码",Toast.LENGTH_LONG).show();
						return;
					}
					
					l.onClick(v,phoneNum,code);
					dismissDialog();
				}
			});
		}
	}
	
	public void setOkButtonOnClickListener(final View.OnClickListener l) {
		if (l == null) {
			return;
		}
		if (mOkButton != null) {
			mOkButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					l.onClick(v);
					dismissDialog();
				}
			});
		}
	}

	public void setCancelButtonOnClickListener(final View.OnClickListener l) {
		if (l == null) {
			return;
		}
		if (mCancelButton != null) {
			mCancelButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					l.onClick(v);
					dismissDialog();
				}
			});
		}
	}

	@Override
    public void show() {
        super.show();
        ColorDrawable dw = new ColorDrawable(0x0000ff00);
        getWindow().setBackgroundDrawable(dw);
        int width = APIProxy.sys().getScreenWidth() * 9 / 10;
        int height = -1;
        getWindow().setLayout(width, height);
    }
	
    private void dismissDialog() {
        AnimationUtilsForCarpool.getInstance().translateTopToBottomReverse(mViewMain, new AnimationListenerForCarpool() {

            @Override
            public void onAnimationEnd(Animation animation) {
                dismiss();
                mSmsUtils.unRegisterSMS();
            }
        });
    }
	
	public interface CallBack{
		
		void onClick(View v, String phone, String code);
	}
}